package com.javaweb.spring.dao.impl;

import com.javaweb.spring.dao.UserDao;
import com.javaweb.spring.pojo.User;
import com.javaweb.spring.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User findByName(String username) {
        /*链接数据库*/
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet=null;
        try {
            /*获取链接*/
            conn = DBUtil.getConnection();
            /*获取预编译的数据库操作对象*/
            String sql = "select * from t_user where username=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            /*执行Sql语句*/
            resultSet = ps.executeQuery();
            /*处理结果集*/
            if (resultSet.next()) {
                String password =resultSet.getString(3);
                return new User(username,password);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                /*释放资源*/
                DBUtil.close(conn, ps, null);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }
}
